<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/5/29
 * Time: 14:03
 */

namespace app\mini\controller;

use app\service\order\Refund;
use JetBrains\PhpStorm\NoReturn;
use think\facade\Log;
use WeChat\Contracts\Tools;
use WePayV3\Order;

class Notify extends Base
{

    public function storeOrder()
    {
        try {
            $serial = request()->header('wechatpay-serial');
            $result    = Order::instance(getWxConfig(['api_cert_serial' => $serial]))->notify();
            $arr = json_decode($result['result'], true);
            //更改订单状态
            $model = \app\company\model\StoreOrder::where('no', $arr['out_trade_no'])->find();
            if(!$model)exception('订单不存在');
            if(in_array($model->order_status,[5,6])){
                //触发退款操作
                (new Refund($model))->update();
                exception('订单已取消');
            }
            $model->order_status = 2;
            $model->save();
        } catch (\Exception $e) {
            Log::error("微信支付回调失败：" . $e->getMessage() . " 文件：" . $e->getFile() . " 行号：" . $e->getLine());
            $this->FAIL();
        }
    }


    /**
     * 返回状态给微信服务器
     */
    #[NoReturn] private function FAIL(): void
    {
        // 返回状态
        $return = ['return_code' =>'FAIL', 'return_msg' => "失败"];
        die($this->toXml($return));
    }


    /**
     * 输出xml字符
     * @param array $values
     * @return bool|string
     */
    private function toXml(array $values): bool|string
    {
        if (count($values) <= 0) return false;
        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }
}